﻿using System;
using NetMicro.Core.ApiFunction;
using NetMicro.Core.Extensions;
using NetMicro.Core.Helper;
using NetMicro.Domains.Tenants;

namespace NetMicro.Domains
{
    /// <summary>
    /// 租户实体基类
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    public abstract class TenantEntityBase<TKey> : EntityBase<TKey>, ITenant<TKey>
    {
        /// <summary>
        /// 租户Id
        /// </summary>
        public TKey TenantId { get; set; }
    }

    /// <summary>
    /// 租户实体基类
    /// </summary>
    public class TenantEntityBase : TenantEntityBase<long>
    {

        /// <summary>
        /// 初始化
        /// </summary>
        public override void Init()
        {
            IsDeleted = false;
            Id = SnowflakeHelper.GetId();
            long data = TimeSpan.Zero.GetTimestampMilliseconds();
            CreateTime = data;
            CreateId = ApiContext.IsAdminApi ? ApiContext.AdminContext.AccountId : ApiContext.WebContext.UserId;
            CreateName = ApiContext.IsAdminApi ? ApiContext.AdminContext.UserName : "";
            UpdateTime = data;
            TenantId = ApiContext.IsAdminApi ? ApiContext.AdminContext.TenantId : ApiContext.WebContext.TenantId;
            Version = 1;
        }
        /// <summary>
        /// 修改初始化
        /// </summary>
        /// <param name="entityBase"></param>
        public override void UpdateInit<TenantEntityBase>(TenantEntityBase entityBase)
        {
            IsDeleted = false;
            Version = entityBase.Version++;
            UpdateId = ApiContext.IsAdminApi ? ApiContext.AdminContext.AccountId : ApiContext.WebContext.UserId;
            UpdateName = ApiContext.IsAdminApi ? ApiContext.AdminContext.UserName : "";
            long data = TimeSpan.Zero.GetTimestampMilliseconds();
            UpdateTime = data;
        }

        /// <summary>
        /// 假删除初始化
        /// </summary>
        /// <param name="entityBase"></param>
        public override void SoftDeleteInit<TenantEntityBase>(TenantEntityBase entityBase)
        {
            IsDeleted = true;
            Version = entityBase.Version++;
            long data = TimeSpan.Zero.GetTimestampMilliseconds();
            UpdateTime = data;
            UpdateId = ApiContext.IsAdminApi ? ApiContext.AdminContext.AccountId : ApiContext.WebContext.UserId;
            UpdateName = ApiContext.IsAdminApi ? ApiContext.AdminContext.UserName : "";
        }
    }
}
